package light.mvc.controller.hrs;

import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.json.JSONArray;
import org.json.JSONException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import light.mvc.controller.base.BaseController;
import light.mvc.framework.constant.GlobalConstant;
import light.mvc.pageModel.base.Grid;
import light.mvc.pageModel.base.Json;
import light.mvc.pageModel.base.PageFilter;
import light.mvc.pageModel.base.SessionInfo;
import light.mvc.pageModel.hrs.HRSData;
import light.mvc.pageModel.hrs.HRSExpert;
import light.mvc.pageModel.hrs.HRSJudgement;
import light.mvc.service.hrs.HRSDataServiceI;
import light.mvc.service.hrs.HRSExpertServiceI;

@Controller
@RequestMapping("/expert")
public class HRSExpertController extends BaseController {
	
	@Autowired
	private HRSExpertServiceI expertService;
	
	@Autowired
	private HRSDataServiceI dataService;
	
	@RequestMapping("/manager")
	public String manager(){
		return "/admin/habitus_research_sys/expert";
	}
	
	//spring自动将参数注入ph对象中
	@RequestMapping("/dataGrid")
	@ResponseBody
	public Grid dataGrid(HRSExpert expert,PageFilter ph){
		Grid grid=new Grid();
		grid.setRows(expertService.dataGrid(expert, ph));
		grid.setTotal(expertService.count(expert, ph));
		return grid;
	}
	
	@RequestMapping("/delete")
	@ResponseBody
	public Json delete(String ids,HttpServletRequest request){
		JSONArray jsonIds;
		Json j=new Json();
		try {
			jsonIds=new JSONArray(ids);
			for(int i=0;i<jsonIds.length();++i){
				long id=jsonIds.getLong(i);
				//获取expertId
				HRSExpert r=expertService.get(id);//这句用处？
				expertService.delete(id, request);
			}
			j.setMsg("删除成功");
			j.setSuccess(true);
		} catch (JSONException e) {
			e.printStackTrace();
			j.setMsg(e.getMessage());
		}catch(Exception e){
			j.setMsg(e.getMessage());
		}
		return j;
		
	}
	@RequestMapping("/detailPage")
	public String detailPage(HttpServletRequest request,Long id){
		HRSExpert r=expertService.get(id);
		request.setAttribute("expert", r);
		return "/admin/habitus_research_sys/expertDetail";
	}
	
//	@RequestMapping(value="/register",method=RequestMethod.POST)
	@RequestMapping(value="/register")
	@ResponseBody
	public HashMap<String, String> register(HRSExpert expert,HttpSession session) {
		HashMap<String, String> res = new HashMap<String, String>();
		
		HRSExpert u=expertService.getByLoginName(expert);
		if(u!=null){
			res.put("result", "fail");
			res.put("tip", "该号码已注册!");
			
		}else{
			expertService.add(expert);
			res.put("result", "success");
			res.put("tip", "注册成功");
			
			SessionInfo sessionInfo=new SessionInfo();
			
			sessionInfo.setRoleType(GlobalConstant.EXPERT);

			HRSExpert registedExpert=expertService.getByLoginName(expert);
			sessionInfo.setId(registedExpert.getId());
			sessionInfo.setSessionId(session.getId());
			sessionInfo.setLoginname(registedExpert.getTel());
			sessionInfo.setName(registedExpert.getName());
			session.setAttribute(GlobalConstant.SESSION_INFO_FRONT_EXPERT, sessionInfo);
			
		}
		return res;
	}

	@RequestMapping("/login")
	@ResponseBody
	public Map<String,Object> login(HRSExpert expert,HttpSession session){
		HashMap<String,Object> res=new HashMap<String,Object>();
		HRSExpert loginExpert=expertService.login(expert);
		if(loginExpert!=null){
			res.put("result","success");
			SessionInfo sessionInfo=new SessionInfo();
			
			sessionInfo.setRoleType(GlobalConstant.EXPERT);
			
			sessionInfo.setId(loginExpert.getId());
			sessionInfo.setSessionId(session.getId());
			sessionInfo.setLoginname(loginExpert.getTel());
			sessionInfo.setName(loginExpert.getName());
			
			session.setAttribute(GlobalConstant.SESSION_INFO_FRONT_EXPERT, sessionInfo);
			
			//res.put("session",sessionInfo);
			
			res.put("sessionid",session.getId());
			
		}
		else{
			res.put("tip", "该号码未注册用户");
			res.put("result","fail");
		}
		return res;
	}


	@RequestMapping("/getAnAskerPic")
	@ResponseBody
	public HashMap<String, Object> getAskerPic(HttpSession session) {
		HashMap<String, Object> res = new HashMap<String, Object>();
		HRSData data = dataService.expertGetOne();
		if(data==null){
			res.put("result","fail");
			res.put("tip", "没有数据");
		}
		else{
			res.put("result", "success");
			res.put("picGroupId", data.getId());
			res.put("facePicUrl", data.getFacePhotoPath());
			res.put("touguePicUrl", data.getTonguePhotoPath());
			res.put("info", "");
		}
		return res;
	}

	@RequestMapping("/uploadJudgement")
	@ResponseBody
	public HashMap<String, String> uploadJudgement(HRSJudgement judgement,HttpSession session) {
		HashMap<String, String> res = new HashMap<String, String>();
//		System.out.println(picGroupId);
		System.out.println("expertId"+judgement.getExpertId());
		System.out.println("picGroupId"+judgement.getPicGroupId()); 

		System.out.println("session "+session.getId()); 
		
		judgement.setJudgementDate(new Date());
		dataService.dataIncrease(judgement.getPicGroupId());
		
		expertService.saveJudgement(judgement);

		res.put("result", "success");
		res.put("tip", "添加成功");
		
		return res;

	}
	@RequestMapping("/add")
	@ResponseBody
	public Json add(HttpServletRequest request,HRSData data,@RequestParam("facePhoto") CommonsMultipartFile facePhoto,@RequestParam("tonguePhoto") CommonsMultipartFile tonguePhoto) {
		SessionInfo sessionInfo = (SessionInfo) request.getSession().getAttribute(GlobalConstant.SESSION_INFO_FRONT_EXPERT);	
		data.setUploaderType(sessionInfo.getRoleType());
		data.setUploaderId(sessionInfo.getId());
		data.setUploadTime(new Date());
		Json j = new Json(); 
//		 获取上传的图片的文件名
        String facePhotoFileName = facePhoto.getOriginalFilename();
        String tonguePhotoFileName = tonguePhoto.getOriginalFilename();
//      获取图片的扩展名
        String facePhotoExtensionName = facePhotoFileName.substring(facePhotoFileName.lastIndexOf(".") + 1);
        String tonguePhotoExtensionName = tonguePhotoFileName.substring(tonguePhotoFileName.lastIndexOf(".") + 1);
//      生成保存的图片文件名
        String facePhotoPrefixName = System.currentTimeMillis()+3+"";
		String facePhotoFilePath=GlobalConstant.uploadFolder+"/"+facePhotoPrefixName+"."+facePhotoExtensionName;//文件路径名
		String facePhotoRealPath = request.getSession().getServletContext().getRealPath("/")+facePhotoFilePath;
        File newFacePhotoFile=new File(facePhotoRealPath);
        String tonguePhotoPrefixName = System.currentTimeMillis()+"";
		String tonguePhotoFilePath=GlobalConstant.uploadFolder+"/"+tonguePhotoPrefixName+"."+tonguePhotoExtensionName;//文件路径名
		String tonguePhotoRealPath = request.getSession().getServletContext().getRealPath("/")+tonguePhotoFilePath;
        File newTonguePhotoFile=new File(tonguePhotoRealPath);
		try {
//          通过CommonsMultipartFile的方法直接写文件
			facePhoto.transferTo(newFacePhotoFile);
			tonguePhoto.transferTo(newTonguePhotoFile);
//			保存文件路径
	        data.setFacePhotoPath(facePhotoFilePath);
	        data.setTonguePhotoPath(tonguePhotoFilePath);
			dataService.add(data);
			j.setSuccess(true);
			j.setMsg("添加成功！");
		} catch (Exception e) {
			j.setMsg(e.getMessage());
		}
		return j;
	}

}
